﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using CADs;
using ModeloGaleriaNET;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para ucAuditoria.xaml
    /// </summary>
    public partial class ucAuditoria : UserControl
    {
        /// <summary>
        /// Indica si el formulario ha sido cargado al menos una vez
        /// </summary>
        private bool loaded;
        /// <summary>
        /// Título del control de usuario que se muestra fuera
        /// </summary>
        private readonly string title = "Auditoría de la aplicación";
        /// <summary>
        /// Número de página actual de la búsqueda
        /// </summary>
        private int pagenum;
        /// <summary>
        /// Número de usuarios existentes en la galería
        /// </summary>
        private int numAuditorias;
        /// <summary>
        /// Número de elementos por página, definido en las propiedades del proyecto
        /// </summary>
        private readonly int pageSize = int.Parse(CADs.Properties.Resources.PageSize);
        /// <summary>
        /// BackgroundWorker. Se usa para trabajar con la base de datos
        /// </summary>
        private BackgroundWorker worker;

        private AuditoriaCAD auditoriaCAD;
        private List<Auditoria> auditorias;

        public ucAuditoria()
        {
            InitializeComponent();
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        }

        public string Title
        {
            get { return title; }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!loaded)
            {
                if (!worker.IsBusy)
                {
                   
                    auditoriaCAD = new AuditoriaCAD();
                    _busyIndicator.IsBusy = true;
                    numAuditorias = -1;
                    pagenum = 0;
                    worker.RunWorkerAsync();
                }
                loaded = true;
            }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                auditorias = auditoriaCAD.GetAuditoriaPaginated(pagenum);
                numAuditorias = auditoriaCAD.GetAuditoriaCount();
            }
            catch (Exception)
            {
                auditorias = null;
                numAuditorias = 0;
            }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
             _busyIndicator.IsBusy = false;
            dgAuditoria.ItemsSource = auditorias;
            tbPaginacion.Visibility = Visibility.Visible;
            UpdatePaginationControls();
            if (auditorias == null)
                Xceed.Wpf.Toolkit.MessageBox.Show("Error!!! No se ha podido realizar la búsqueda", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void btSiguiente_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                pagenum++;
                worker.RunWorkerAsync();
            }
        }

        private void btSiguiente_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtSiguiente != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Right_24.GetHbitmap() : Properties.Resources.RightBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtSiguiente.Source = bs;
            }
        }

        private void btAnterior_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                pagenum--;
                worker.RunWorkerAsync();
            }
        }

        private void btAnterior_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtAnterior != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Left_24.GetHbitmap() : Properties.Resources.LeftBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtAnterior.Source = bs;
            }
        }

        private void UpdatePaginationControls()
        {
            String iniString = "0";
            String deString = "";

            if (numAuditorias > 0)
                iniString = (pagenum * pageSize + 1).ToString();

            btAnterior.IsEnabled = pagenum == 0 ? false : true;

            if (pagenum + 1 >= numAuditorias / (float)pageSize)
            {
                btSiguiente.IsEnabled = false;
                deString = numAuditorias.ToString();
            }
            else
            {
                btSiguiente.IsEnabled = true;
                deString = ((pagenum + 1) * pageSize).ToString();
            }

            lbPagina.Content = iniString + " - " + deString + " de " + numAuditorias;
        }

        private void btLimpiar_Click(object sender, RoutedEventArgs e)
        {
            _busyIndicator.IsBusy = true;
            auditoriaCAD.SetQueryFilters(null);
            numAuditorias = -1;
            pagenum = 0;
            worker.RunWorkerAsync();
        }

        private void btBuscar_Click(object sender, RoutedEventArgs e)
        {
            AuditoriaFilterWindow busqueda;

            busqueda = new AuditoriaFilterWindow();
            busqueda.ShowDialog();

            if (busqueda.Success) // Realizar búsqueda
            {
                if (!worker.IsBusy)
                {
                    _busyIndicator.IsBusy = true;
                    auditoriaCAD.SetQueryFilters(busqueda.Filters);
                    dgAuditoria.ItemsSource = null;
                    dgAuditoria.Items.Clear();
                    numAuditorias = -1;
                    pagenum = 0;
                    worker.RunWorkerAsync();
                }
            }
        }
    }
}
